import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  // const userToken = store.state.User.token
  const userToken = JSON.parse(sessionStorage.getItem('token'))
  if (userToken) {
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['Token'] = userToken
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => response,
  // code为非10000时抛错,可结合自己业务进行修改
  // console.log(response)
  const res = response.data
  if (res.code !== 200) {
    if (res.code === 0 || res.code === 500) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 3 * 1000
      })
    }
    // 4045:Token 过期
    // if (res.code === '4050' || res.code === '4051') {
    // 	MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
    // 		confirmButtonText: '重新登录',
    // 		cancelButtonText: '取消',
    // 		type: 'warning'
    // 	}).then(() => {
    // 		store.dispatch('User/logout').then(() => {
    // 			// 登出跳倒mp登录页面
    // 			window.location.href = SYSTEM.USER.LOGINJUMP
    // 		})
    // 	})
    // } else {
    // 	Message({
    // 		message: res.message,
    // 		type: 'error',
    // 		duration: 3 * 1000
    // 	})
    // }
    return Promise.reject(res)
  } else {
    return response
  }
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
